package com.tuxing.draa_data.service.draa;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.base.Strings;
import com.tuxing.draa_data.common.DraaContent;
import com.tuxing.draa_data.dao.*;
import com.tuxing.draa_data.dao.center.*;
import com.tuxing.draa_data.pojo.*;
import com.tuxing.draa_data.pojo.center.*;
import com.tuxing.draa_data.util.ConvertUtil;
import com.tuxing.draa_data.util.FormatUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * @author YuanShiHang
 * @version 1.0
 * @className FormalDataServiceImpl
 * @description 基础描述: DRAA正式数据入库服务实现
 * @date 2021/11/18 19:40
 */
@Service
@Slf4j
public class FormalDataServiceImpl implements FormalDataService {

    @Resource
    private DraaTemporaryDataDao draaTemporaryDataDao;

    @Resource
    private NewDcBibliographyPeriDao newDcBibliographyPeriDao;

    @Resource
    private NewDcBibliographyPeriDetailDao newDcBibliographyPeriDetailDao;

    @Resource
    private DraaTemporaryBookDao draaTemporaryBookDao;

    @Resource
    private NewDcBibliographyBookDao newDcBibliographyBookDao;

    @Resource
    private NewDcBibliographyBookDetailDao newDcBibliographyBookDetailDao;

    @Resource
    private NewDcECollectionDao newDcECollectionDao;

    @Resource
    private NewDcPackageDao newDcPackageDao;

    @Resource
    private NewDcBookDao newDcBookDao;

    @Resource
    private NewDcPeriDao newDcPeriDao;

    //region 期刊数据解析

    /**
     * @return 无返回结果
     * @decpription 进行DRAA数据的去重及正式数据保存
     * @author YuanShiHang
     * @date 2021/11/18 19:46
     * @version 1.0
     */
    @Override
    public void saveFormalJournalData() {
        List<NewDcECollection> allDatabase = newDcECollectionDao.findAll();
        Map<String, NewDcECollection> dbMap = allDatabase.stream().collect(Collectors.toMap(NewDcECollection::getSourceId, s -> s));

        int maxId = 0;
        int pageStart = 1;
        while (true) {
            int offset = pageStart * 1000;
            log.info("读取临时表数据偏移量：" + offset + ",最大ONLY_AUTO值为：" + maxId);
            List<DraaTemporaryJournal> temporaryDataList = draaTemporaryDataDao.findListByPage(maxId);
            if (!CollectionUtils.isEmpty(temporaryDataList)) {

                temporaryDataList.sort(Comparator.comparing(DraaTemporaryJournal::getId).reversed());
                //获取当前批次最大值
                maxId = temporaryDataList.get(temporaryDataList.size() - 1).getId();

                for (DraaTemporaryJournal temporaryJournal : temporaryDataList) {
                    try {

                        if (!temporaryJournal.getDatatype().contains("期刊")) {
                            continue;
                        }


                    } catch (Exception ex) {
                        log.error("保存数据错误，错误原因：" + ex.getMessage(), ex);
                        log.info("错误数据：" + JSONObject.toJSON(temporaryJournal));
                    }
                }

                if (temporaryDataList.size() < 1000) {
                    break;
                }
                pageStart++;
            } else {
                break;
            }
        }
    }

    /**
     * @param noRepeatOne  draa的临时数据
     * @param dataTypeLang 该draa数据对应的数据库的语种
     * @return 无返回结果
     * @decpription 判断draa临时数据在正式数据中是否存在，并调用保存
     * @author YuanShiHang
     * @date 2021/11/19 14:40
     * @version 1.0
     */
    private NewDcBibliographyPeri checkJournalRepeatAndSave(DraaTemporaryBook noRepeatOne, Integer dataTypeLang) {

        NewDcBibliographyPeri oneByDraaJid = newDcBibliographyPeriDao.findOneByDraaJid(noRepeatOne.getErId());
        if (oneByDraaJid != null) {
            return oneByDraaJid;
        }
        //issn和online_issn号进行format处理
        String pIssn = FormatUtil.formatISSN(noRepeatOne.getPIssn());
        String eIssn = FormatUtil.formatISSN(noRepeatOne.getEIssn());

        noRepeatOne.setPIssn(pIssn);
        noRepeatOne.setEIssn(eIssn);

        //2.根据print_issn进行检索匹配，如果有对应期刊信息直接返回（这部分要改动：后期先根据期刊DOI进行匹配）
        if (!Strings.isNullOrEmpty(pIssn)) {
            NewDcBibliographyPeri oneByPISSN = newDcBibliographyPeriDao.findOneByPISSN(pIssn, dataTypeLang);
            if (oneByPISSN != null) {
                return oneByPISSN;
            }
        }

        //3.再根据online_issn进行匹配，如果有直接返回期刊信息
        if (!Strings.isNullOrEmpty(eIssn)) {
            NewDcBibliographyPeri oneByEISSN = newDcBibliographyPeriDao.findOneByEISSN(eIssn);
            if (oneByEISSN != null) {
                return oneByEISSN;
            } else {
                //4.再根据期刊题名进行检索
                NewDcBibliographyPeri oneByTitle = newDcBibliographyPeriDao.findCnOneByTitle(noRepeatOne.getTitle(), dataTypeLang);
                if (oneByTitle != null) {
                    return oneByTitle;
                } else {
                    return saveJournalData(noRepeatOne, dataTypeLang);
                }
            }
        } else {
            //5.如果没有online_issn号可以直接通过题名检索
            NewDcBibliographyPeri oneByTitle = newDcBibliographyPeriDao.findCnOneByTitle(noRepeatOne.getTitle(), dataTypeLang);
            if (oneByTitle != null) {
                return oneByTitle;
            } else {
                return saveJournalData(noRepeatOne, dataTypeLang);
            }
        }
    }

    private void saveJournalRelation(NewDcBibliographyPeri peri, NewDcPackage newDcPackage, DraaTemporaryBook temporaryJournal) {

        String vYear = temporaryJournal.getYear();
        int yearInt = ConvertUtil.objToInt(vYear, 2022);
        NewDcPeri newDcPeri = newDcPeriDao
                .findOneByBidDidPidYear(peri.getRecordId(), newDcPackage.getCollectionId(), newDcPackage.getPackageId(), yearInt);
        if (newDcPeri == null) {
            newDcPeri = new NewDcPeri();
            newDcPeri.create(peri.getRecordId(), peri.getLangCode(), newDcPackage, yearInt, temporaryJournal);
            newDcPeriDao.insert(newDcPeri);
            log.info("新增期刊库包清单关系：" + newDcPeri);
        }
    }

    /**
     * @param noRepeatOne draa的临时数据
     * @return 无返回结果
     * @decpription 进行draa正式数据的SQL保存
     * @author YuanShiHang
     * @date 2021/11/19 14:39
     * @version 1.0
     */
    private NewDcBibliographyPeri saveJournalData(DraaTemporaryBook noRepeatOne, Integer dataTypeLang) {
        try {

            NewDcBibliographyPeri peri = new NewDcBibliographyPeri();
            peri.create(noRepeatOne, dataTypeLang);
            newDcBibliographyPeriDao.insert(peri);
            Long recordId = peri.getRecordId();
            NewDcBibliographyPeriDetail periDetail = new NewDcBibliographyPeriDetail();
            periDetail.create(recordId, noRepeatOne);
            newDcBibliographyPeriDetailDao.insert(periDetail);
            log.info("保存期刊数据：" + peri);
            return peri;
        } catch (Exception ex) {
            log.error("保存数据错误，错误原因：" + ex.getMessage(), ex);
            log.info("保存错误临时数据：" + JSON.toJSONString(noRepeatOne));
        }
        return null;
    }

    //endregion

    //region 图书数据解析

    @Resource
    private NewDcDatabasePropertyDao newDcDatabasePropertyDao;

    /**
     * @return 无返回结果
     * @decpription 进行图书数据的清洗和保存
     * @author YuanShiHang
     * @date 2021/12/1 14:22
     * @version 1.0
     */
    @Override
    public void saveFormalBookData() {

        List<NewDcECollection> allDatabase = newDcECollectionDao.findAll();
        Map<String, NewDcECollection> dbMap = allDatabase.stream().filter(s -> s.getSource() == 0).collect(Collectors.toMap(NewDcECollection::getSourceId, s -> s));
        List<NewDcDatabaseProperty> newDcDatabaseProperties = newDcDatabasePropertyDao.selectList(null);
        Map<Long, Integer> dbLangMap = newDcDatabaseProperties.stream().collect(Collectors.toMap(NewDcDatabaseProperty::getDId, NewDcDatabaseProperty::getLangId, (k1, k2) -> k1));

        Integer maxId = 1002142;
        int pageStart = 1002;
        while (true) {
            int offset = pageStart * 1000;
            log.info("读取临时表数据偏移量：" + offset + ",最大ID为：" + maxId);
            List<DraaTemporaryBook> bookList = draaTemporaryBookDao.findListByPage(maxId);
            if (CollectionUtils.isNotEmpty(bookList)) {

                //获取下次进行分页查询时的最大ID值，进行深度翻页
                bookList.sort(Comparator.comparing(DraaTemporaryBook::getId).reversed());
                maxId = bookList.get(0).getId();

                //循环处理DRAA的图书数据
                for (DraaTemporaryBook temporaryBook : bookList) {
                    try {
                        if (temporaryBook.getDatatype().contains("图书")) {
                            saveDraaBookData(temporaryBook, dbMap, dbLangMap);
                        } else if (temporaryBook.getDatatype().contains("期刊")) {
                            saveDraaJournalData(temporaryBook, dbMap, dbLangMap);
                        }
                    } catch (Exception ex) {
                        log.error("保存数据错误，错误原因：" + ex.getMessage(), ex);
                        log.info("错误数据：" + JSONObject.toJSON(temporaryBook));
                    }
                }
                if (bookList.size() < 1000) {
                    break;
                }
                pageStart++;
            } else {
                break;
            }
        }
    }

    private void saveDraaJournalData(DraaTemporaryBook temporaryBook, Map<String, NewDcECollection> dbMap, Map<Long, Integer> dbLangMap) {
        NewDcECollection ec = dbMap.get(temporaryBook.getDbErId());
        if (ec == null) {
            return;
        }

        Integer lang = dbLangMap.get(ec.getCollectionId());
        Integer dataTypeLang = lang == 1 ? 1 : 3;

        NewDcBibliographyPeri peri = checkJournalRepeatAndSave(temporaryBook, dataTypeLang);

        Long cid = ec.getCollectionId();

        //判断资源包信息
        NewDcPackage newDcPackage = checkAndSavePackageInfo(temporaryBook.getPackageOuId(), temporaryBook.getMinimumUnit(),
                temporaryBook.getLevel(), cid);

        saveJournalRelation(peri, newDcPackage, temporaryBook);
    }

    private void saveDraaBookData(DraaTemporaryBook temporaryBook, Map<String, NewDcECollection> dbMap, Map<Long, Integer> dbLangMap) {
        NewDcECollection ec = dbMap.get(temporaryBook.getDbErId());
        if (ec == null) {
            return;
        }
        Integer lang = dbLangMap.get(ec.getCollectionId());
        Integer dataTypeLang = lang == 1 ? 2 : 4;

        //判断保存
        NewDcBibliographyBook dcBook = checkRepeatBookAndSave(temporaryBook, dataTypeLang);

        //判断资源包信息
        NewDcPackage newDcPackage = checkAndSavePackageInfo(temporaryBook.getPackageOuId(), temporaryBook.getMinimumUnit(), temporaryBook.getLevel(), ec.getCollectionId());

        saveBookRelation(dcBook, newDcPackage, temporaryBook);
    }

    @Override
    public void formatJournalIncludeRange() {
        QueryWrapper<NewDcPeri> periQueryWrapper = new QueryWrapper<>();
        periQueryWrapper.eq("SOURCE_TYPE", 1);
        periQueryWrapper.last("limit 108700,1900000");
        List<NewDcPeri> newDcPeriList = newDcPeriDao.selectList(periQueryWrapper);

        Pattern r = Pattern.compile("([0-9]{4})");
        int i = 108700;
        for (NewDcPeri newDcPeri : newDcPeriList) {
            String scopeBegin = newDcPeri.getScopeBegin();
            String scopeEnd = newDcPeri.getScopeEnd();
            String timeScope = newDcPeri.getTimeScope();
            String[] timeScopeArray = null;
            if (!Strings.isNullOrEmpty(timeScope)) {
                timeScopeArray = timeScope.split("-");
            }

            /*
            重新定义收录起始时间
             */
            //如果不为空，那么就将其处理为后面收录范围的起始时间
            if (!Strings.isNullOrEmpty(scopeBegin)) {
                switch (scopeBegin) {
                    case "无":
                    case "":
                    case "null":
                    case "NULL":
                    case "至今":
                    case "-":
                    case "_":
                        if (timeScopeArray != null && timeScopeArray.length > 0) {
                            scopeBegin = timeScopeArray[0];
                        }
                        break;
                    default:
                        break;
                }
            } else {
                if (timeScopeArray != null && timeScopeArray.length > 0) {
                    scopeBegin = timeScopeArray[0];
                }
            }
            if (!Strings.isNullOrEmpty(scopeBegin)) {
                Matcher mBegin = r.matcher(scopeBegin);
                if (mBegin.find()) {
                    scopeBegin = mBegin.group(0);
                } else {
                    scopeBegin = null;
                }
            }

            /*
            重新定义收录结束时间
             */
            int delay = 0;
            //如果不为空，那么就将其处理为后面收录范围的结束时间
            if (!Strings.isNullOrEmpty(scopeEnd)) {
                switch (scopeEnd) {
                    case "无":
                    case "":
                    case "null":
                    case "NULL":
                    case "-":
                    case "_":
                        //如果收录截止时间没有，就设置为null
                        if (timeScopeArray != null && timeScopeArray.length > 1) {
                            scopeEnd = timeScopeArray[1];
                        } else {
                            scopeEnd = null;
                        }
                        break;
                    case "滞后":
                        //如果滞后，标识收录范围结束时间为至今
                        //如果收录截止时间没有，就设置为null
                        if (timeScopeArray != null && timeScopeArray.length > 1) {
                            scopeEnd = timeScopeArray[1];
                        } else {
                            scopeEnd = null;
                        }
                        delay = 1;
                    case "至今":
                        //如果收录截止时间是至今，那就去看看范围中有没有后面的时间，有就赋值
                        if (timeScopeArray != null && timeScopeArray.length > 1) {
                            scopeEnd = timeScopeArray[1];
                        }
                        if (!Strings.isNullOrEmpty(scopeEnd) && !scopeEnd.equals("至今")) {
                            Matcher mEnd = r.matcher(scopeEnd);
                            if (mEnd.find()) {
                                scopeEnd = mEnd.group(0);
                                if (ConvertUtil.objToInt(scopeEnd) < ConvertUtil.objToInt(scopeBegin)) {
                                    scopeEnd = "至今";
                                }
                            } else {
                                scopeEnd = "至今";
                            }
                        }
                        break;
                    default:
                        break;
                }
            } else {
                if (timeScopeArray != null && timeScopeArray.length > 1) {
                    scopeEnd = timeScopeArray[1];
                } else {
                    scopeEnd = null;
                }
            }

            if (!Strings.isNullOrEmpty(scopeEnd) && !scopeEnd.equals("至今")) {
                Matcher mEnd = r.matcher(scopeEnd);
                if (mEnd.find()) {
                    scopeEnd = mEnd.group(0);
                } else {
                    scopeEnd = null;
                }
            } else {
                if (!Strings.isNullOrEmpty(scopeBegin)) {
                    scopeEnd = "至今";
                }
            }

            if (!Strings.isNullOrEmpty(scopeBegin)) {
                if (Strings.isNullOrEmpty(scopeEnd)) {
                    scopeEnd = "至今";
                }
                timeScope = scopeBegin + "-" + scopeEnd;
                Integer delayFromDb = newDcPeri.getDelay();
                if (delay == 1 && (delayFromDb == null || delayFromDb <= 0)) {
                    delayFromDb = delay;
                }
                newDcPeri.setDelay(delayFromDb);
            }

            newDcPeri.setScopeBegin(scopeBegin);
            newDcPeri.setScopeEnd(scopeEnd);
            newDcPeri.setTimeScope(timeScope);

            newDcPeriDao.updateById(newDcPeri);
            System.out.println("处理数据：" + i);
            i++;
        }
    }

    @Override
    public void formatJournal() {
        QueryWrapper<NewDcBibliographyPeri> periQueryWrapper = new QueryWrapper<>();
        periQueryWrapper.eq("DATA_TYPE", 0).eq("LANG_CODE", 3);
        int i = 0;
        int b = 1;
        List<NewDcBibliographyPeri> periList = newDcBibliographyPeriDao.selectList(periQueryWrapper);
        for (NewDcBibliographyPeri peri : periList) {
            System.out.println("已处理：" + b);
            b++;
            NewDcBibliographyPeri asSamePeri = findAsSamePeriId(peri);
            if (asSamePeri != null) {
                newDcPeriDao.updateByRecordId(asSamePeri.getRecordId(), peri.getRecordId());
                newDcBibliographyPeriDetailDao.deleteById(peri.getRecordId());
                newDcBibliographyPeriDao.deleteById(peri);
                log.info("删除期刊：" + peri.toString());
                i++;
                System.out.println("删除期刊数量：" + i);
            }

        }
    }

    @Override
    public void formatJournalName() {
        QueryWrapper<NewDcBibliographyPeri> periQueryWrapper = new QueryWrapper<>();
        periQueryWrapper.last("order by TITLE ASC LIMIT 1000");
        List<NewDcBibliographyPeri> periList = newDcBibliographyPeriDao.selectList(periQueryWrapper);
        for (NewDcBibliographyPeri peri : periList) {
            String title = peri.getTitle();
            String journalName = FormatUtil.formatJournalName(title);
            System.out.println(journalName);
        }
    }

    private NewDcBibliographyPeri findAsSamePeriId(NewDcBibliographyPeri thePeri) {
        Integer langCode = thePeri.getLangCode();
        String pissn = thePeri.getPIssn();
        if (!Strings.isNullOrEmpty(pissn)) {
            QueryWrapper<NewDcBibliographyPeri> issnWrapper = new QueryWrapper<>();
            issnWrapper.eq("P_ISSN", pissn).eq("LANG_CODE", langCode);
            issnWrapper.ne("DATA_TYPE", 0);
            issnWrapper.last("limit 1");
            NewDcBibliographyPeri peri = newDcBibliographyPeriDao.selectOne(issnWrapper);
            if (peri != null) {
                if (langCode == 1) {
                    if (Strings.isNullOrEmpty(peri.getOIssn()) && !Strings.isNullOrEmpty(thePeri.getOIssn())) {
                        peri.setOIssn(thePeri.getOIssn());
                        peri.setMagId(thePeri.getMagId());
                        newDcBibliographyPeriDao.updateById(peri);
                    }
                }
                if (langCode == 3) {
                    if (Strings.isNullOrEmpty(peri.getPeriCnNo()) && !Strings.isNullOrEmpty(thePeri.getPeriCnNo())) {
                        peri.setPeriCnNo(thePeri.getPeriCnNo());
                        peri.setMagId(thePeri.getMagId());
                        newDcBibliographyPeriDao.updateById(peri);
                    }
                }
                return peri;
            }
        }
        if (langCode == 3) {
            String cn = thePeri.getPeriCnNo();
            if (!Strings.isNullOrEmpty(cn)) {
                QueryWrapper<NewDcBibliographyPeri> cnWrapper = new QueryWrapper<>();
                cnWrapper.eq("PERI_CN_NO", cn).eq("LANG_CODE", langCode);
                NewDcBibliographyPeri peri = getNewDcBibliographyPeri(thePeri, cnWrapper);
                if (peri != null) return peri;
            }
        } else {
            String oIssn = thePeri.getOIssn();
            if (!Strings.isNullOrEmpty(oIssn)) {
                QueryWrapper<NewDcBibliographyPeri> oissnWrapper = new QueryWrapper<>();
                oissnWrapper.eq("O_ISSN", oIssn).eq("LANG_CODE", langCode);
                NewDcBibliographyPeri peri = getNewDcBibliographyPeri(thePeri, oissnWrapper);
                if (peri != null) return peri;
            }
        }
        String title = thePeri.getTitle();
        if (!Strings.isNullOrEmpty(title)) {
            QueryWrapper<NewDcBibliographyPeri> titleWrapper = new QueryWrapper<>();
            titleWrapper.eq("TITLE", title).eq("LANG_CODE", langCode);
            titleWrapper.ne("DATA_TYPE", 0);
            titleWrapper.last("limit 1");
            return newDcBibliographyPeriDao.selectOne(titleWrapper);
        }
        return null;
    }

    private NewDcBibliographyPeri getNewDcBibliographyPeri(NewDcBibliographyPeri thePeri, QueryWrapper<NewDcBibliographyPeri> cnWrapper) {
        cnWrapper.ne("DATA_TYPE", 0);
        cnWrapper.last("limit 1");
        NewDcBibliographyPeri peri = newDcBibliographyPeriDao.selectOne(cnWrapper);
        if (peri != null) {
            if (Strings.isNullOrEmpty(peri.getPIssn()) && !Strings.isNullOrEmpty(thePeri.getPIssn())) {
                peri.setPIssn(thePeri.getPIssn());
                peri.setMagId(thePeri.getMagId());
                newDcBibliographyPeriDao.updateById(peri);
            }
            return peri;
        }
        return null;
    }

    private void saveBookRelation(NewDcBibliographyBook dcBook, NewDcPackage newDcPackage, DraaTemporaryBook temporaryBook) {
        String vYear = temporaryBook.getYear();
        int yearInt = ConvertUtil.objToInt(vYear, 2022);
        NewDcBook newDcBook = newDcBookDao
                .findOneByBidDidPidYear(dcBook.getRecordId(), newDcPackage.getCollectionId(), newDcPackage.getPackageId(), yearInt);
        if (newDcBook == null) {
            newDcBook = new NewDcBook();
            newDcBook.create(dcBook.getRecordId(), dcBook.getLangCode(), newDcPackage, yearInt, temporaryBook);
            newDcBookDao.insert(newDcBook);
            log.info("新增图书库包清单关系：" + newDcBook);
        }
    }


    /**
     * @return 新的订购包
     * @decpription 进行订购包判断和保存
     * @author yuanshihang
     * @date 2021/12/6 14:52
     * @version 1.0
     */
    private NewDcPackage checkAndSavePackageInfo(String packageOuId, String minimumUnit, String level,
                                                 Long cid) {

        NewDcPackage oneByDraaPidCid = newDcPackageDao.findOneByDraaPidCid(packageOuId, cid);
        if (oneByDraaPidCid == null) {
            oneByDraaPidCid = new NewDcPackage();
            oneByDraaPidCid.create(cid, packageOuId, minimumUnit, level, DraaContent.OrderSource.FROM_DRAA);
            newDcPackageDao.insert(oneByDraaPidCid);
            log.info("新增资源包：" + oneByDraaPidCid);
        }
        return oneByDraaPidCid;
    }


    /**
     * @param noRepeatOne 待比对临时数据
     * @return 无返回结果
     * @decpription 进行临时数据重复比对和保存
     * @author yuanshihang
     * @date 2021/12/1 16:20
     * @version 1.0
     */
    private NewDcBibliographyBook checkRepeatBookAndSave(DraaTemporaryBook noRepeatOne, Integer lang) {

        //查询DRAABID一致的图书在正式表中有没有重复，如果重新直接跳过
        NewDcBibliographyBook oneByDraaBid = newDcBibliographyBookDao.findOneByDraaBid(noRepeatOne.getErId());
        if (oneByDraaBid != null) {
            return oneByDraaBid;
        }

//        String issnIsbn = noRepeatOne.getIssnIsbn();
//        String[] splitByBr = null;
//        if (!Strings.isNullOrEmpty(issnIsbn)) {
//            splitByBr = issnIsbn.split("<br>");
//        }
        String pIsbn = noRepeatOne.getPIsbn();
//        if (Strings.isNullOrEmpty(pIsbn) && splitByBr != null) {
//            pIsbn = splitByBr[0];
//        }
        String eIsbn = noRepeatOne.getEIsbn();
//        if (Strings.isNullOrEmpty(eIsbn) && splitByBr != null) {
//            if (splitByBr.length > 1) {
//                eIsbn = splitByBr[1];
//            }
//        }

        pIsbn = FormatUtil.formatISBN(pIsbn);
        eIsbn = FormatUtil.formatISBN(eIsbn);

        //数据回填
        noRepeatOne.setPIsbn(pIsbn);
        noRepeatOne.setEIsbn(eIsbn);

        //如果pIsbn有值，进行pIsbn的查询
        if (StringUtils.isNotBlank(pIsbn)) {

            //根据pIsbn号进行检索
            NewDcBibliographyBook oneByPISBN = newDcBibliographyBookDao.findOneByPISBN(pIsbn, lang);
            if (oneByPISBN != null) {
                return oneByPISBN;
            }

        }

        //如果没有重复的，如果eIsbn号存在再根据eIsbn号进行检索
        if (StringUtils.isNotBlank(eIsbn)) {
            NewDcBibliographyBook oneByEISBN = newDcBibliographyBookDao.findOneByEISBN(eIsbn, lang);

            //如果没有的重复的，最后再根据图书名称进行检索，没有重复就进行数据保存
            if (oneByEISBN == null) {
                NewDcBibliographyBook oneByTitle = newDcBibliographyBookDao.findOneByTitle(noRepeatOne.getTitle(), lang);
                if (oneByTitle == null) {
                    return saveBookData(noRepeatOne, lang);
                } else {
                    return oneByTitle;
                }
            } else {
                return oneByEISBN;
            }

        } else {
            //如果eIsbn号为空，直接根据图书名称进行检索
            NewDcBibliographyBook oneByTitle = newDcBibliographyBookDao.findOneByTitle(noRepeatOne.getTitle(), lang);
            if (oneByTitle == null) {
                return saveBookData(noRepeatOne, lang);
            } else {
                return oneByTitle;
            }
        }
//        return null;

    }

    /**
     * @param noRepeatOne draa的临时数据
     * @return 无返回结果
     * @decpription 进行draa正式数据的SQL保存
     * @author YuanShiHang
     * @date 2021/11/19 14:39
     * @version 1.0
     */
    private NewDcBibliographyBook saveBookData(DraaTemporaryBook noRepeatOne, Integer lang) {
        try {
            NewDcBibliographyBook newDcBibliographyBook = new NewDcBibliographyBook();
            newDcBibliographyBook.create(noRepeatOne, lang);
            newDcBibliographyBookDao.insert(newDcBibliographyBook);
            Long recordId = newDcBibliographyBook.getRecordId();

            NewDcBibliographyBookDetail newDcBibliographyBookDetail = new NewDcBibliographyBookDetail();
            newDcBibliographyBookDetail.create(recordId, noRepeatOne);
            newDcBibliographyBookDetailDao.insert(newDcBibliographyBookDetail);
            log.info("保存图书数据：" + newDcBibliographyBook);
            return newDcBibliographyBook;
        } catch (Exception ex) {
            log.error("保存数据错误，错误原因：" + ex.getMessage(), ex);
            log.info("保存错误临时数据：" + JSON.toJSONString(noRepeatOne));
        }
        return null;
    }

    //endregion


}
